package com.igogogo.web.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.igogogo.utils.ResultJson;

@RestController
@RequestMapping(value = "file")
public class FileController {

	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public ResultJson uploads(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		ResultJson json = new ResultJson();
		if (file != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."),
					file.getOriginalFilename().length());
			String fileName = sdf.format(new Date()) + fileExt;
			String filePath = request.getSession().getServletContext().getRealPath("uploads/");
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath, fileName));
				json.setMsgcode(200);
				json.setMsginfo("success");
				json.setResult(fileName);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return json;
	}

}
